#include "mstp_types.h"
#include <stdio.h>
#include <stdio.h>

#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sched.h>

extern void printalloc(void);

int main(void)
{
    mstp_t mstp_sock;
    struct sockaddr_in addr;
    struct timeval start, end;
    u_int8_t buffer[1024*4096];
    u_int32_t x;
    u_int32_t total = 0;
    int fd;
    
    addr.sin_family = AF_INET;
    addr.sin_port   = htons(2000);
    inet_aton("200.43.15.229", &addr.sin_addr);
    
    if (mstp_socket(&mstp_sock) == -1)
	perror("mstp_socket()");

    if (mstp_bind(&mstp_sock, &addr) == -1)
	perror("mstp_bind()");
	
    if (mstp_accept(&mstp_sock,16) == -1)
	perror("mstp_accept()");



    gettimeofday(&start, NULL);    

    fd = open ("pimpim.txt", O_CREAT | O_WRONLY);

    while (1) {

	x = mstp_recv(&mstp_sock, buffer, 128*1024);
	write(fd, buffer, x);
	total += x;
	
	gettimeofday(&end, NULL);
    
	printf ("Average Speed: %.2f mbps/s - Total bytes: %d\n", ((float)(total)/(end.tv_sec-start.tv_sec)/(1024*1024))*8, total);

	if (x == 0)
	    break;
	
	if (x == -1) {
	    perror("Error");
	    break;
	}
    }
    
    print_max_atomic();
    
    close(fd);
    return 0;

}
